/*
 The MIT License
 
 Copyright InScopeApps{+} 2009.
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:
 
 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

#import "PrefsController.h"

#define kAppPreview @"CopyPath.app"
#define kDocPreview @"notes.txt"
#define kKOVnew     @"new"

@implementation PrefsController

@synthesize presetsArray;

#pragma mark -
#pragma mark setup
- (void)awakeFromNib{
    [prefsWindow setFloatingPanel:YES];
    
    //set info text
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *infoString = [[NSString alloc] initWithFormat:@"\n%@ %@\n%@", 
                            [infoDictionary objectForKey:@"CFBundleName"],
                            [infoDictionary objectForKey:@"CFBundleVersion"],
                            [infoDictionary objectForKey:@"CFBundleGetInfoString"]];
    info.stringValue = infoString;
    [infoString release];
    
    //TODO: format the info text
    
    //load prefs
    prefs = [[Prefs alloc] init];
    [self setUpObservers];
    [prefs loadDefaults];
    
    //load presets
    presetsArray = [[NSMutableArray alloc] init];
    [self loadPresetList];
}

//find all plists in the presets directory
- (void)loadPresetList{
    NSString *bundleRoot = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:kPresetDir];
    NSArray *dirContents = [[NSFileManager defaultManager] directoryContentsAtPath:bundleRoot];
    for (NSString *fileItem in dirContents){
        if ([[fileItem pathExtension] isEqualTo:kPListExt]){
            [presetsArray addObject:[fileItem stringByDeletingPathExtension]];
        }
    }
}

#pragma mark -
#pragma mark preset combo box
- (NSInteger)numberOfItemsInComboBox:(NSComboBox *)aComboBox {
    return [presetsArray count];
}
- (id)comboBox:(NSComboBox *)aComboBox objectValueForItemAtIndex:(NSInteger)index {
    return [presetsArray objectAtIndex:index];
}
- (NSUInteger)comboBox:(NSComboBox *)aComboBox indexOfItemWithStringValue:(NSString *)string {
    return [presetsArray indexOfObject:string];
}

#pragma mark -
#pragma mark update ui
- (void)setUpObservers{
    [prefs addObserver:self forKeyPath:kPrefsPre options:NSKeyValueObservingOptionNew context:nil];
    [prefs addObserver:self forKeyPath:kPrefsPost options:NSKeyValueObservingOptionNew context:nil];
    [prefs addObserver:self forKeyPath:kPrefsPreBlock options:NSKeyValueObservingOptionNew context:nil];
    [prefs addObserver:self forKeyPath:kPrefsPostBlock options:NSKeyValueObservingOptionNew context:nil];
    [prefs addObserver:self forKeyPath:kPrefsSearch options:NSKeyValueObservingOptionNew context:nil];
    [prefs addObserver:self forKeyPath:kPrefsReplace options:NSKeyValueObservingOptionNew context:nil];
    [prefs addObserver:self forKeyPath:kPrefsSpacer options:NSKeyValueObservingOptionNew context:nil];
    [prefs addObserver:self forKeyPath:kPrefsDent options:NSKeyValueObservingOptionNew context:nil];
    [prefs addObserver:self forKeyPath:kPrefsTruncate options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if(object == prefs){
        if([keyPath isEqual:kPrefsPre]){
            pre.stringValue = [change objectForKey:kKOVnew];
        }
        else if([keyPath isEqual:kPrefsPost]){
            post.stringValue = [change objectForKey:kKOVnew];
        }
        else if([keyPath isEqual:kPrefsPreBlock]){
            preBlock.stringValue = [change objectForKey:kKOVnew];
        }
        else if([keyPath isEqual:kPrefsPostBlock]){
            postBlock.stringValue = [change objectForKey:kKOVnew];
        }
        else if([keyPath isEqual:kPrefsSearch]){
            search.stringValue = [change objectForKey:kKOVnew];
        }
        else if([keyPath isEqual:kPrefsReplace]){
            replace.stringValue = [change objectForKey:kKOVnew];
        }
        else if([keyPath isEqual:kPrefsSpacer]){
            if([[change objectForKey:kKOVnew] isEqualTo:kNewline]){
                newline.state = NSOnState;
            }
            else{
                newline.state = NSOffState;
            }
        }
        else if([keyPath isEqual:kPrefsDent]){
            if([[change objectForKey:kKOVnew] isEqualTo:kTab]){
                dent.state = NSOnState;
            }
            else{
                dent.state = NSOffState;
            }
        }
        else if([keyPath isEqual:kPrefsTruncate]){
            truncate.intValue = [[change objectForKey:kKOVnew] intValue];
        }
    }
    
    [self updatePreview];
}

- (void)updatePreview{
    inscp_paths *previewPaths = [[inscp_paths alloc] init];
    
    NSArray *applicationsDirectories = NSSearchPathForDirectoriesInDomains(NSAllApplicationsDirectory, NSLocalDomainMask, YES);
    if ([applicationsDirectories count] > 0){
        [previewPaths addPath:[[applicationsDirectories objectAtIndex:0] stringByAppendingPathComponent:kAppPreview]];
    }
    NSArray *documentDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if ([documentDirectories count] > 0){
        [previewPaths addPath:[documentDirectories objectAtIndex:0]];
        [previewPaths addPath:[[documentDirectories objectAtIndex:0] stringByAppendingPathComponent:kDocPreview]];
    }
    
    preview.stringValue = [previewPaths formatPathsWithPrefs:prefs];
    
    [previewPaths release];
}

#pragma mark -
#pragma mark IB actions
- (IBAction)valueChanged:(id)sender{
    //pre/post
    if(sender == pre){
        prefs.pre = pre.stringValue;
    }
    else if(sender == post){
        prefs.post = post.stringValue;
    }
    
    //pre/post block
    else if(sender == preBlock){
        prefs.preBlock = preBlock.stringValue;
    }
    else if(sender == postBlock){
        prefs.postBlock = postBlock.stringValue;
    }
    
    //search/replace
    else if(sender == search){
        prefs.search = search.stringValue;
    }
    else if(sender == replace){
        prefs.replace = replace.stringValue;
    }
    
    else if(sender == truncate){
        prefs.truncate = truncate.integerValue;
    }
}

#pragma mark -
#pragma mark checkboxes
- (IBAction)endLineChanged:(id)sender{
    if(newline.state == NSOnState){
        prefs.spacer = kNewline;
    }
    else{
        prefs.spacer = kBlank;
    }
}

- (IBAction)indentChanged:(id)sender{
    if(dent.state == NSOnState){
        prefs.dent = kTab;
    }
    else{
        prefs.dent = kBlank;
    }
}

- (IBAction)switchPreset:(id)sender{
    [prefs loadFromPreset:presets.stringValue];
    presets.stringValue = kBlank;
}

- (IBAction)clearFields:(id)sender{
    [prefs clear];
}

#pragma mark -
#pragma mark close window
- (IBAction)close:(id)sender{
    [prefs setDefaults];
    
    Copy *copy = [[Copy alloc] init];
    [copy copyPathsWithModifier:YES];
    [copy release];
    
    [NSApp terminate:self];
}

- (void)dealloc{
    [presetsArray release];
    
    [super dealloc];
}

@end
